package yxy.apple.nio;

import io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandler.ClientHandshakeStateEvent;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler.HandshakeComplete;
import io.netty.handler.ssl.SslHandshakeCompletionEvent;

public abstract class LayeredHandler extends Handler {
	public static enum Layer {
		Default, SSL, WebSocket, SSLWebSocket;
	}

	@Override
	protected void active() throws Exception {
		Layer layer = layer();
		if (layer == Layer.SSL || layer == Layer.WebSocket || layer == Layer.SSLWebSocket) {
			//对有承载协议层的消息进行拦截，等待握手完成再回调激活
		} else {
			super.active();
		}
	}

	@Override
	protected void trigger(Object event) throws Exception {
		Layer layer = layer();
		if (layer == Layer.SSL) {
			if (event != null && event instanceof SslHandshakeCompletionEvent) {
				super.active();
			}
		} else if (layer == Layer.WebSocket || layer == Layer.SSLWebSocket) {
			if (event != null) {
				if (event instanceof ClientHandshakeStateEvent
						&& event == ClientHandshakeStateEvent.HANDSHAKE_COMPLETE) {// as client
					super.active();
				} else if (event instanceof HandshakeComplete) {// as server
					super.active();
				}
			}
		} else {
			super.trigger(event);
		}
	}

	protected abstract Layer layer();

}
